<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>分类参数</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片区域 -->
    <el-card class="box-card">
      <!-- 警告消息 -->
      <el-alert show-icon :cloasble="false" title="注意: 只允许为第三级分类设置相关参数!" type="warning"></el-alert>

      <!-- 选择商品分类下拉框 -->
      <el-row>
        <rl-col>
          <span>选择商品分类 :</span>
          <el-cascader
            v-model="selectKeys"
            :options="cateList"
            :props="catProps"
            @change="handleChange"
          ></el-cascader>
        </rl-col>
      </el-row>

      <!-- tab标签区域 -->
      <el-tabs v-model="activeName" @tab-click="tabClick">
        <!-- 动态参数区域 -->
        <el-tab-pane label="动态参数" name="many">
          <!-- 添加参数按钮 -->
          <el-button
            type="primary"
            @click="addDialogVisible = true"
            plain
            :disabled="isBtnDisabled"
          >添加参数</el-button>
          <!-- 动态参数表格 -->
          <el-table :data="manyTableData" border stripe style="width: 100%">
            <!-- 展开行 -->
            <el-table-column type="expand">
              <template slot-scope="scope">
                <!-- tag标签 -->
                <el-tag
                  @close="removeVals(index,scope.row)"
                  v-for="(item,index) in scope.row.attr_vals"
                  :key="index"
                  closable
                >{{item}}</el-tag>
                <!-- 输入框添加新的属性 -->
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                ></el-input>
                <!-- 点击切换输入框 -->
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(scope.row)"
                >+ New Tag</el-button>
              </template>
            </el-table-column>
            <el-table-column type="index" label="#"></el-table-column>
            <el-table-column prop="attr_name" label="参数名称"></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button
                  @click="showEditDialog(scope.row.attr_id)"
                  plain
                  size="mini"
                  type="success"
                  icon="el-icon-edit"
                >编辑</el-button>
                <el-button
                  @click="removeParams(scope.row.attr_id)"
                  plain
                  size="mini"
                  type="danger"
                  icon="el-icon-delete"
                >删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>

        <!-- 静态属性区域 -->
        <el-tab-pane label="静态属性" name="only">
          <!-- 添加属性按钮 -->
          <el-button
            type="primary"
            @click="addDialogVisible = true"
            plain
            :disabled="isBtnDisabled"
          >添加属性</el-button>
          <!-- 静态属性表格 -->
          <el-table :data="onlyTableData" border stripe style="width: 100%">
            <!-- 展开行 -->
            <el-table-column type="expand">
              <template slot-scope="scope">
                <!-- tag标签 -->
                <el-tag
                  @close="removeVals(index,scope.row)"
                  v-for="(item,index) in scope.row.attr_vals"
                  :key="index"
                  closable
                >{{item}}</el-tag>
                <!-- 输入框添加新的属性 -->
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                ></el-input>
                <!-- 点击切换输入框 -->
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(scope.row)"
                >+ New Tag</el-button>
              </template>
            </el-table-column>
            <el-table-column type="index" label="#"></el-table-column>
            <el-table-column prop="attr_name" label="参数名称"></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button
                  @click="showEditDialog(scope.row.attr_id)"
                  plain
                  size="mini"
                  type="success"
                  icon="el-icon-edit"
                >编辑</el-button>
                <el-button
                  @click="removeParams(scope.row.attr_id)"
                  plain
                  size="mini"
                  type="danger"
                  icon="el-icon-delete"
                >删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>

    <!-- 添加参数对话框 -->
    <el-dialog
      @close="addDialogClosed"
      :title="'添加' + titleText"
      :visible.sync="addDialogVisible"
      width="50%"
    >
      <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="100px">
        <el-form-item :label="titleText" prop="attr_name">
          <el-input v-model="addForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addParams">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 编辑参数对话框 -->
    <el-dialog
      @close="editDialogClosed"
      :title="'修改' + titleText"
      :visible.sync="editDialogVisible"
      width="50%"
    >
      <el-form :model="editForm" :rules="editFormRules" ref="editFormRef" label-width="100px">
        <el-form-item :label="titleText" prop="attr_name">
          <el-input v-model="editForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editParams">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'Params',
  data() {
    return {
      // 商品分类数据列表
      cateList: [],
      // 下拉框的配置对象
      catProps: {
        value: 'cat_id',
        label: 'cat_name',
        children: 'children',
        expandTrigger: 'hover'
      },
      // 下拉列表所选中的分类id
      selectKeys: [],
      // 默认选中的tab标签
      activeName: 'many',

      // 动态参数数据
      manyTableData: [],
      // 静态属性数据
      onlyTableData: [],

      // 显示隐藏添加参数对话框
      addDialogVisible: false,
      // 添加参数表单数据
      addForm: {
        attr_name: ''
      },
      // 添加参数表单验证规则
      addFormRules: {
        attr_name: [{ required: true, message: '请输入参数名称', trigger: 'blur' }]
      },

      // 显示隐藏编辑对话框
      editDialogVisible: false,
      // 编辑参数数据
      editForm: {
        attr_name: ''
      },
      // 编辑参数验证规则
      editFormRules: {
        attr_name: [{ required: true, message: '请输入参数名称', trigger: 'blur' }]
      },

      // 控制输入框的显示隐藏
      inputVisible: false,
      // 输入框输入绑定的值
      inputValue: ''
    }
  },
  created() {
    this.getCateList()
  },
  methods: {
    // 获取商品分类数据
    async getCateList() {
      const { data: res } = await this.$http.get('/categories')
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      // console.log(res)
      this.cateList = res.data
    },
    // 抽取一个方法获取参数数据,handleChange和tabClick共用的方法
    async getParamsData() {
      // 如果selectKeys的长度不等于三,说明选中的不是三级分类
      if (this.selectKeys.length !== 3) {
        this.selectKeys = []
        this.manyTableData = []
        this.onlyTableData = []
        return
      }
      const { data: res } = await this.$http.get(`/categories/${this.cateId}/attributes`, {
        params: { sel: this.activeName }
      })
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      // 对返回的数据进行格式化
      res.data.forEach(item => {
        // split字符串分割成数组
        item.attr_vals = item.attr_vals ? item.attr_vals.split(' ') : []
        item.inputVisible = false
        item.inputValue = ''
      })
      console.log(res.data)
      if (this.activeName === 'many') {
        this.manyTableData = res.data
      } else {
        this.onlyTableData = res.data
      }
    },
    // 监听下拉列表的改变的值
    async handleChange() {
      this.getParamsData()
    },
    // 监听tab被选中触发的事件
    tabClick() {
      this.getParamsData()
    },

    // 重置添加参数表单
    addDialogClosed() {
      this.$refs.addFormRef.resetFields()
    },
    // 实现添加参数
    addParams() {
      this.$refs.addFormRef.validate(async valid => {
        if (!valid) return
        const { data: res } = await this.$http.post(`categories/${this.cateId}/attributes`, {
          attr_name: this.addForm.attr_name,
          attr_sel: this.activeName
        })
        if (res.meta.status !== 201) return this.$message.error(res.meta.msg)
        this.$message.success(res.meta.msg)
        this.getParamsData()
        this.addDialogVisible = false
      })
    },

    // 显示编辑对话框
    async showEditDialog(id) {
      const { data: res } = await this.$http.get(`categories/${this.cateId}/attributes/${id}`, {
        params: { attr_sel: this.activeName }
      })
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.editForm = res.data
      this.editDialogVisible = true
    },
    // 重置编辑对话框
    editDialogClosed() {
      this.$refs.editFormRef.resetFields()
    },
    // 完成编辑功能
    editParams() {
      this.$refs.editFormRef.validate(async valid => {
        if (!valid) return
        const { data: res } = await this.$http.put(`categories/${this.cateId}/attributes/${this.editForm.attr_id}`, {
          attr_name: this.editForm.attr_name,
          attr_sel: this.activeName
        })
        if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
        this.getParamsData()
        this.editDialogVisible = false
      })
    },

    // 完成删除功能
    async removeParams(id) {
      const confirmResult = await this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      if (confirmResult !== 'confirm') {
        return this.$message.error('取消删除成功')
      }
      const { data: res } = await this.$http.delete(`/categories/${this.cateId}/attributes/${id}`)
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.getParamsData()
    },

    // 输入框失去焦点,或enter键按下后出发的事件
    async handleInputConfirm(paramsInfo) {
      if (paramsInfo.inputValue.trim().length === 0) {
        paramsInfo.inputValue = ''
        paramsInfo.inputVisible = false
        return false
      }
      paramsInfo.attr_vals.push(paramsInfo.inputValue.trim())
      paramsInfo.inputValue = ''
      paramsInfo.inputVisible = false
      this.saveParams(paramsInfo)
    },
    // 发送请求提取成一个方法
    async saveParams(paramsInfo) {
      const { data: res } = await this.$http.put(`categories/${paramsInfo.cat_id}/attributes/${paramsInfo.attr_id}`, {
        attr_name: paramsInfo.attr_name,
        attr_sel: paramsInfo.attr_sel,
        // join数组分割成字符串
        attr_vals: paramsInfo.attr_vals.join(' ')
      })
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      // this.getParamsData()
    },
    // 显示输入框
    showInput(paramsInfo) {
      paramsInfo.inputVisible = true
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus()
      })
    },
    // 删除参数
    removeVals(i, paramsInfo) {
      paramsInfo.attr_vals.splice(i, 1)
      this.saveParams(paramsInfo)
    }
  },

  // 计算属性
  computed: {
    // 控制按钮的禁用
    isBtnDisabled() {
      if (this.selectKeys.length !== 3) {
        return true
      }
      return false
    },

    // 获取商品分类参数的id,发送请求
    cateId() {
      if (this.selectKeys.length === 3) {
        return this.selectKeys[2]
      }
      return null
    },
    // 动态参数和静态属性切换
    titleText() {
      if (this.activeName === 'many') {
        return '动态参数'
      }
      return '静态属性'
    }
  }
}
</script>

<style lang="less" scoped>
.el-alert {
  margin-bottom: 20px;
}
.el-cascader {
  width: 300px;
  margin-left: 10px;
}
.el-tabs {
  margin-top: 20px;
}
.el-tag {
  margin-right: 10px;
}
.input-new-tag {
  width: 150px;
}
</style>
